package SM.Controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Hex;

import SM.BusinessLogic.DBAccess;
import SM.BusinessLogic.DBService;
import SM.BusinessLogic.SessionVariables;


/**
 * Servlet implementation class ReportIssue
 */

public class LoginAuth extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public LoginAuth() {
        
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// doPost is used to Accept request from page and Make Changes
		
		String user = request.getParameter("username");
		String password = request.getParameter("password");
		String id = request.getParameter("id");
		PrintWriter out = response.getWriter();
		
		if(id == null || user == null || password == null)
		{
			System.out.println("Error while reading parameters of login");
			return;
		}
		
		if(id.equals("signin"))
		{
			String sha1Pass = new String();
			
			try {
				sha1Pass = GetHash(password);
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if(SignIn(user, sha1Pass))
			{
				SessionVariables.SetUser(user, request);
				response.sendRedirect("User/home");
			}
			else
			{
				out.println("<html><body><span style='color:red;'>Please Go Back.. " +
						"Your Login is unsuccessful</span></body></html>");
			}
		}
		else if(id.equals("signup"))
		{
			if(SignUp(user, password))
			{
				response.sendRedirect("index.html");
			}
			else
			{
				out.println("<html><body><span style='color:red;'>Please Go Back.. User ID " + user + " " +
						"is already present..\nCannot signup again </span></body></html>");
			}
		}
		
		
	}
	
	private boolean SignIn(String user, String password)
	{
		String loginQuery = "select * from Credentials where username = ? and password = ?";
		
		if(DBService.IsRecordPresent(loginQuery, user, password))
		{
			//here forward to home
			return true;
		}
		else
		{
			//here login invalid
			return false;
		}
	}
	
	private boolean SignUp(String user, String password)
	{
		String loginQuery = "select * from Credentials where username = ? and password = ?";
		
		if(DBService.IsRecordPresent(loginQuery, user, password))
		{
			//here reject the user name as it is present
			return false;
		}
		else
		{
			//here enter data
			String insertQuery = "insert into Credentials(username,password,role) values(?,?,?)";
			String sha1Pass = new String();
			
			try {
				sha1Pass = GetHash(password);
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			Connection connection = null;
			PreparedStatement statement = null;
			
			try
			{
				connection = DBAccess.MakeConnection();
				
				statement = connection.prepareStatement(insertQuery);
				
				statement.setString(1, user);
				statement.setString(2, sha1Pass);
				statement.setInt(3, 0);
				
				statement.executeUpdate();
				
			}catch(SQLException SQLEx)
			{
				System.out.println("SQLException in execute insert query\nError : " + SQLEx.getMessage());
			}
			finally
			{
				DBAccess.CloseConnection(connection);
				DBAccess.CloseStatement(statement);
			}
			
			return true;
		}
	}
	
	private String GetHash(String tobeHashed) throws NoSuchAlgorithmException,UnsupportedEncodingException
	{
		//return sha1 hash
		MessageDigest cript = MessageDigest.getInstance("SHA-1");
        cript.reset();
        cript.update(tobeHashed.getBytes("utf8"));
        String hash = new String(Hex.encodeHex(cript.digest()));
        return hash;
	}

}
